// pages/shopping/shopping/shopping.js
const { getShoppingHttp, postShoppingHttp } = require("../../../utils/http")
const { bewriteStr } = require("../../../utils/utils")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    drink: [],
    isDel: false,
    checked: false,
    total: 0,
    isShow: true
  },
  onChangeCheckedAll(event) {
    this.setData({
      checked: event.detail,
    });
  },
  handleCheckedAll() {
    let drink = this.data.drink
    let checked = this.data.checked
    drink.forEach(item => {
      item.checked = checked == true ? true : false
    })
    this.addTotal()
    this.setData({ drink })
  },
  pass(e) {
    let aid = e.detail
    let drink = this.data.drink
    let checked = this.data.checked
    drink.forEach(item => {
      if (item._id !== aid) return
      item.checked = !item.checked
    })
    this.addTotal()
    checked = drink.every(item => {
      return item.checked == true
    })

    this.setData({ drink, checked })
  },
  handleManageClick(e) {
    this.setData({
      isDel: !this.data.isDel
    })
  },
  async handleSubmmit(e) {
    let drink = this.data.drink
    let idArr = []
    drink.forEach(item => {
      if (item.checked === true) {
        idArr.push(item._id)
      }
    })
    let data = {
      idArr: JSON.stringify(idArr),
      addbuy: false,
      num: 1
    }
    let isDel = this.data.isDel
    if (isDel) {
      //删除
      await postShoppingHttp.postShoppingGoodsHttp(data)
      this.getDrink()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  async getDrink() {
    let drinks = await getShoppingHttp.getShoppingGoodsHttp()
    let drink = drinks.data.res
    drink.forEach(item => {
      item.bewrite = bewriteStr(item.bewrite)
    })
    let isShow = this.data.isShow
    if (drink.length === 0) {
      isShow = true
    } else {
      isShow = false
    }
    this.setData({ drink, isShow })
  },
  addTotal() {
    let drink = this.data.drink
    let total = 0
    drink.forEach(item => {
      if (item.checked) {
        total += Number(item.price * item.num)
      }
    })
    this.setData({ total: total * 100 })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getDrink()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})